#include "alone_key.h"
#include "c51.h"
#include "common.h"
#include "utils.h"

u8 alone_key_scan(void) {
  u8 num = 0;
  if (P3_1 == 0) {
    delay(20);
    while (P3_1 == 0) {
    }
    delay(20);
    num = 1;
  }

  if (P3_0 == 0) {
    delay(20);
    while (P3_0 == 0) {
    }
    delay(20);
    num = 2;
  }

  if (P3_2 == 0) {
    delay(20);
    while (P3_2 == 0) {
    }
    delay(20);
    num = 3;
  }

  if (P3_3 == 0) {
    delay(20);
    while (P3_3 == 0) {
    }
    delay(20);
    num = 4;
  }

  return num;
}

static u8 key;

u8 alone_key_state() {
  u8 num = 0;
  if (P3_1 == 0) {

    num = 1;
  }

  if (P3_0 == 0) {
    num = 2;
  }

  if (P3_2 == 0) {
    num = 3;
  }

  if (P3_3 == 0) {
    num = 4;
  }
  return num;
}

void alone_key_loop(void) {
  static u8 now, prev;
  prev = now;
  now = alone_key_state();
  if (prev == 1 && now == 0) {
    key = 1;
  }

  if (prev == 2 && now == 0) {
    key = 2;
  }

  if (prev == 3 && now == 0) {
    key = 3;
  }

  if (prev == 4 && now == 0) {
    key = 4;
  }
}

u8 alone_key_get() {
  u8 temp;
  temp = key;
  key = 0;
  return temp;
}
